<?php

namespace app\admin\model\weixin;

use think\Model;
use addons\weixin\library\WechatService;

class Reply extends Model
{
    // 表名
    protected $name = 'weixin_reply';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];

    public function getTypeList()
    {
        // return ['text' => __('Text'), 'image' => __('Image'), 'news' => __('News'), 'voice' => __('Voice')];
        //只保留图文回复
         return ['news' => __('News')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 整理文本输入的消息
     * @param $data
     * @param $key
     * @return array|bool
     */
    public function tidyText($data, $key)
    {
        $res = [];
        $res['content'] = $data['content'];
        return json_encode($res);
    }

    /**
     * 整理图片资源
     * @param $data
     * @param $key
     * @return array|bool|mixed
     */
    public function tidyImage($data, $key)
    {
        $data['src'] = $data['image'];
        unset($data['image']);
        $reply = self::get(['key' => $key]);
        if ($reply) {
            $reply['data'] = json_decode($reply['data'], true);
        }
        if ($reply && isset($reply['data']['src']) && $reply['data']['src'] == $data['src']) {
            $res = $reply['data'];
        } else {
            $res = [];
            //TODO 图片转media
            $res['src'] = $filePath = $data['src'];
            $info = pathinfo($filePath);
            $trueFileName = $_SERVER['DOCUMENT_ROOT'] . '/' . $info['dirname'] . '/' . $info['basename'];
            $material = WechatService::materialService()->uploadImage($trueFileName);
            $res['media_id'] = $material->media_id;
        }
        return json_encode($res);
    }

    /**
     * 整理声音资源
     * @param $data
     * @param $key
     * @return array|bool|mixed
     */
    public function tidyVoice($data, $key)
    {
        $data['src'] = $data['voice'];
        unset($data['voice']);
        $reply = self::get(['key' => $key]);
        if ($reply) {
            $reply['data'] = json_decode($reply['data'], true);
        }
        if ($reply && isset($reply['data']['src']) && $reply['data']['src'] == $data['src']) {
            $res = $reply['data'];
        } else {
            $res = [];
            //TODO 声音转media
            $res['src'] = $filePath = $data['src'];
            $info = pathinfo($filePath);
            $trueFileName = $_SERVER['DOCUMENT_ROOT'] . '/' . $info['dirname'] . '/' . $info['basename'];
            $material = WechatService::materialService()->uploadVoice($trueFileName);
            $res['media_id'] = $material->media_id;
        }
        return json_encode($res);
    }

    /**
     * 整理图文资源
     * @param $data
     * @param $key
     * @return bool
     */
    public function tidyNews($data, $key = '')
    {
        $newsModel = new \app\admin\model\weixin\News;
        $news_id = $data['news'];
        $row = $newsModel->get($news_id);
        if (!$row) {
            return false;
        }
        $data = [
            'id' => $row['id'],
            'title' => $row['cate_name'],
            'description' => $row['description'],
            'url' => $row['url'] ? $row['url'] : 'http://' . $_SERVER['HTTP_HOST'],
            'image' => $row['image']
        ];
        if (strpos($data['image'], 'http') === false) {
            $data['image'] = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $data['image'];
        }
        return json_encode($data);
    }


    /**
     * 获取关键字
     * @param $key
     * @param string $default
     * @return array|\EasyWeChat\Message\Image|\EasyWeChat\Message\News|\EasyWeChat\Message\Text|\EasyWeChat\Message\Voice
     */
    public static function reply($key, $default = '')
    {


        //$res = self::where('key', $key)->where('status', '1')->find();
        $res = self::where(['key'=>$key,'wxid'=>$default])->where('status', '1')->find();

        if (empty($res)) {
            $res = self::where('key', 'default')->where('status', '1')->find();
        }
        if (empty($res)) {
            return WechatService::transfer();
        }
        $res['data'] = json_decode($res['data'], true);
        if ($res['type'] == 'text') {
            if (isset($res['data']['content']) && $res['data']['content']) {
                return WechatService::textMessage($res['data']['content']);
            } else {
                return self::reply('default');
            }
        } elseif ($res['type'] == 'image') {
            if (isset($res['data']['media_id']) && $res['data']['media_id']) {
                return WechatService::imageMessage($res['data']['media_id']);
            } else {
                return self::reply('default');
            }
        } elseif ($res['type'] == 'news') {
            if (isset($res['data']) && $res['data']) {
                return WechatService::newsMessage($res['data']);
            } else {
                return self::reply('default');
            }
        } elseif ($res['type'] == 'voice') {
            if (isset($res['data']['media_id']) && $res['data']['media_id']) {
                return WechatService::voiceMessage($res['data']['media_id']);
            } else {
                return self::reply('default');
            }
        }
    }



    /**
     * 获取关键字
     * @param $key
     * @param string $default
     * @return array|\EasyWeChat\Message\Image|\EasyWeChat\Message\News|\EasyWeChat\Message\Text|\EasyWeChat\Message\Voice
     */
    public static function replyold($key, $default = '')
    {
        $res = self::where('key', $key)->where('status', '1')->find();
        if (empty($res)) {
            $res = self::where('key', 'default')->where('status', '1')->find();
        }
        if (empty($res)) {
            return WechatService::transfer();
        }
        $res['data'] = json_decode($res['data'], true);
        if ($res['type'] == 'text') {
            if (isset($res['data']['content']) && $res['data']['content']) {
                return WechatService::textMessage($res['data']['content']);
            } else {
                return self::reply('default');
            }
        } elseif ($res['type'] == 'image') {
            if (isset($res['data']['media_id']) && $res['data']['media_id']) {
                return WechatService::imageMessage($res['data']['media_id']);
            } else {
                return self::reply('default');
            }
        } elseif ($res['type'] == 'news') {
            if (isset($res['data']) && $res['data']) {
                return WechatService::newsMessage($res['data']);
            } else {
                return self::reply('default');
            }
        } elseif ($res['type'] == 'voice') {
            if (isset($res['data']['media_id']) && $res['data']['media_id']) {
                return WechatService::voiceMessage($res['data']['media_id']);
            } else {
                return self::reply('default');
            }
        }
    }
}
